import socket
import select


proxy_server = ("1.1.1.1", 8080)           # 代理地址

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 8081))                  # 监听地址
server.listen(4)
socks = []
clients = []


def host_format(host):
    return f"{host[0]}:{host[1]}"


while True:
    close_flag = []
    rs, wx, xs = select.select([server] + socks + clients, [], [], 0.1)
    for _rs in rs:
        if _rs == server:
            sock, host = _rs.accept()
            print("Recv host:", host)
            socks.append(sock)

            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client.connect(proxy_server)
            clients.append(client)
            continue
        index = socks.index(_rs) if _rs in socks else clients.index(_rs)
        buf = _rs.recv(1024)
        if buf:
            if _rs in socks:
                print(f"{host_format(_rs.getpeername())} -> "
                      f"{host_format(_rs.getsockname())}({host_format(clients[index].getsockname())}):", buf)
                clients[index].send(buf)
            else:
                print(f"{host_format(_rs.getsockname())} <- {host_format(_rs.getpeername())}:", buf)
                socks[index].send(buf)
        else:
            clients[index].close()
            socks[index].close()
            close_flag.append(index)

    for i in close_flag[::-1]:
        socks.pop(i)
        clients.pop(i)
        close_flag = []
